package models;

import java.awt.Component;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;

import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.TransferHandler;


@SuppressWarnings("serial")
public class ListTransferHandler extends TransferHandler {
	
	ModelMyPlayer model;
	
	public ListTransferHandler(ModelMyPlayer model){
		this.model = model;
	}

    @Override
    public boolean canImport(TransferSupport support) {
    	if (support.getComponent() instanceof JSlider) {
        	return (support.getComponent() instanceof JSlider) && support.isDataFlavorSupported(ListItemTransferable.LIST_ITEM_DATA_FLAVOR);
        } else if (support.getComponent() instanceof JPanel) {
        	return (support.getComponent() instanceof JPanel) && support.isDataFlavorSupported(ListItemTransferable.LIST_ITEM_DATA_FLAVOR);
        }
        return (support.getComponent() instanceof JPanel) && support.isDataFlavorSupported(ListItemTransferable.LIST_ITEM_DATA_FLAVOR);
    }

    @Override
    public boolean importData(TransferSupport support) {
        boolean accept = false;
        if (canImport(support)) {
            try {
                Transferable t = support.getTransferable();
                Object value = t.getTransferData(ListItemTransferable.LIST_ITEM_DATA_FLAVOR);
                if (value instanceof ListItem) {
                    Component component = support.getComponent();
                    if (component instanceof JSlider) {
                    	model.setSrc(((ListItem)value).getText());
                    } else if (component instanceof JPanel) {
                    	model.setSrc(((ListItem)value).getText());
                    }
                } 
            } catch (Exception exp) {
                exp.printStackTrace();
            }
        }
        return accept;
    }

    @Override
    public int getSourceActions(JComponent c) {
        return DnDConstants.ACTION_COPY_OR_MOVE;
    }

	@SuppressWarnings("rawtypes")
	@Override
    protected Transferable createTransferable(JComponent c) {
        Transferable t = null;
        if (c instanceof JList) {
            JList list = (JList) c;
            Object value = list.getSelectedValue();
            if (value instanceof ListItem) {
                ListItem li = (ListItem) value;
                t = new ListItemTransferable(li);
            }
        }
        return t;
    }

    @Override
    protected void exportDone(JComponent source, Transferable data, int action) {
        // Here you need to decide how to handle the completion of the transfer,
        // should you remove the item from the list or not...
    }
}